<template>
  <div class="wrap">
    <div style="margin-bottom:10px;">
      <el-date-picker
        :editable="false"
        :picker-options="pickerOptions"
        value-format="yyyy-MM-dd"
        v-model="dateValue"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="dateChange">
      </el-date-picker>
      <!-- <el-select v-model="productId" placeholder="产品" style="width:120px;" @change="productChange">
            <el-option
            v-for="item in productNameOption"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select> -->
       <el-input placeholder="请输入产品名称" style="width:200px;" v-model="productName"></el-input>

      <el-button icon="el-icon-refresh" @click="refreshClick" style="margin-left:20px;">刷新</el-button>
    </div>
    <el-table
      class="table"
      border fit highlight-current-row
      v-loading="loading"
      element-loading-text="加载中"
      element-loading-spinner="el-icon-loading"
      :data="tableData"
      style="width: 100%">
      <el-table-column type="expand" width="30">
         <template slot-scope="props">
              <el-form label-position="left" class="demo-table-expand">
                  <el-form-item label="产品名称">
                      <span>{{ props.row.productName }}</span>
                  </el-form-item>
                  <el-form-item label="产品后台">
                      <span>{{ props.row.productAdminUrl }}</span>
                  </el-form-item>
                  <el-form-item label="产品账号">
                      <span>{{ props.row.productAccount }}</span>
                  </el-form-item>
                  <el-form-item label="产品密码">
                      <span>{{ props.row.productPassword }}</span>
                  </el-form-item>
              </el-form>
               
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
          align="center"
          width="100"
          label="日期">
          <template slot-scope="scope">
            <p>{{_mapping.date_format2(scope.row.createTime)}}</p>
          </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="100"
        prop="productName"
        label="产品">
      </el-table-column>
      <el-table-column
        align="center"
        label="应结注册|应结UV|应结下款">
        <template slot-scope="scope">
          <span>{{scope.row.realCpaNum || 0}} | {{scope.row.realUvNum || 0}} | {{scope.row.realCpsNum || 0}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="结算方式|单价">
        <template slot-scope="scope">
           <p v-if="scope.row.settlementType ===0"> CPA | {{scope.row.settlementPrice || 0}}</p>
           <p v-if="scope.row.settlementType ===1"> UV | {{scope.row.settlementPrice || 0}}</p>
           <p v-if="scope.row.settlementType ===2"> CPS | {{scope.row.settlementPrice || 0}}</p>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        :label="`UV|转化率|收益 ${this.tab.productUvNumTotal || 0} | ${this.tab.productUvRateAve ? this.tab.productUvRateAve+'%' : '-'} | ${this.tab.productBenifitRateTotal ? this.tab.productBenifitRateTotal : '-'}`"
        :render-header="renderHeader3">
        <template slot-scope="scope">
          <span>{{scope.row.uvNum || 0}} | {{isNaN((scope.row.realCpaNum*100/scope.row.uvNum).toFixed(1)) ? '-' : ((scope.row.realCpaNum*100/scope.row.uvNum).toFixed(1))+'%'}} </span>
          <span v-if="scope.row.settlementType">| {{isNaN((scope.row.realUvNum*scope.row.settlementPrice/scope.row.realUvNum).toFixed(1)) ? '-' : ((scope.row.realUvNum*scope.row.settlementPrice/scope.row.realUvNum).toFixed(1))}}</span>
          <span v-else>| {{isNaN((scope.row.realCpaNum*scope.row.settlementPrice/scope.row.realUvNum).toFixed(1)) ? '-' : ((scope.row.realCpaNum*scope.row.settlementPrice/scope.row.realUvNum).toFixed(1))}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="`15sUV|扣量 ${this.tab.regisNumTotal || 0} | ${this.tab.reduceAve ? this.tab.reduceAve+'%' : '-'}`"
        :render-header="renderHeader2">
        <template slot-scope="scope">
          <span>{{scope.row.cpaNum || 0}}</span>
          <span v-if="scope.row.settlementType">| {{'-'}}</span>
          <span v-else>| {{isNaN(((scope.row.cpaNum-scope.row.realCpaNum)*100/scope.row.cpaNum).toFixed(1)) ? '-' : (((scope.row.cpaNum-scope.row.realCpaNum)*100/scope.row.cpaNum).toFixed(1))+'%'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="`应结金额 ${this.tab.payNumTotal || 0}`"
        :render-header="renderHeader1">
        <template slot-scope="scope">
          <span v-if="scope.row.settlementType===1">{{(scope.row.realUvNum*scope.row.settlementPrice).toFixed(1)}}</span>
          <span v-if ="scope.row.settlementType===0">{{(scope.row.realCpaNum*scope.row.settlementPrice).toFixed(1)}}</span>
          <span v-if ="scope.row.settlementType===2">{{(scope.row.realCpsNum*scope.row.settlementPrice).toFixed(1)}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="balanceMoney"
        label="结余金额">
      </el-table-column>
      <el-table-column
        align="center"
        prop="noSettlementMoney"
        label="未结金额">
      </el-table-column>
      <el-table-column
        align="center"
        prop="createByName"
        label="商务">
      </el-table-column>
      <el-table-column
        align="center"
        label="状态">
        <template slot-scope="scope">
          <span :style="{color:(colorMap[scope.row.settlementStatus + ''])}">{{settlementStatusMap[scope.row.settlementStatus + '']}} | </span>
          <span :style="{color:(colorMap[scope.row.status + ''])}">{{statusMap[scope.row.status + '']}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="300"
        label="操作">
        <template slot-scope="scope">
          <el-button style="font-size:12px;" @click="fillClick(scope.row)">录入</el-button>
          <el-button style="font-size:12px;" @click="toSettlement(scope.row)">结算</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="clearfix pagination" style="margin-top:30px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pageNum"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum">
      </el-pagination>
    </div>
    <el-dialog title="录入" :close-on-click-modal="false" :visible.sync="dialogVisible" width="70%" class="dialog">
        <el-row class="line">
            <el-col :span="5" class="label">日期</el-col>
            <el-col :span="5">{{fillData.date}}</el-col>
        </el-row>
        <el-row class="line">
            <el-col :span="5" class="label">产品名称</el-col>
            <el-col :span="5">{{fillData.productName}}</el-col>
        </el-row>
        <el-row class="line" >
            <el-col :span="5" class="label" style="line-height:30px;">
                <span><span class="red">*</span>CPA数</span>
            </el-col>
            <el-col :span="5">
                <el-input placeholder="请输入CPA数" v-model="fillData.realCpaNum"></el-input>
            </el-col>
        </el-row>

       <el-row class="line" >
            <el-col :span="5" class="label" style="line-height:30px;">
                <span><span class="red">*</span>CPS数</span>
            </el-col>
            <el-col :span="5">
                <el-input placeholder="请输入CPS数" v-model="fillData.realCpsNum"></el-input>
            </el-col>
        </el-row>

        <el-row class="line">
            <el-col :span="5" class="label">修改UV数</el-col>
            <el-col :span="5">
                <el-switch v-model="fillData.uvSwitch"></el-switch>
                <p style="color:#f00; margin-top:5px;">如非特殊情况请勿修改</p>
            </el-col>
        </el-row>
        <el-row class="line" v-show="fillData.uvSwitch">
            <el-col :span="5" class="label" style="line-height:30px;">
                <span><span class="red">*</span>UV数</span>
            </el-col>
            <el-col :span="5">
                <el-input placeholder="请输入UV数" v-model="fillData.realUvNum"></el-input>
            </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="fillConfirm">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
import _product from '@/services/product.js'
import _base from '@/services/base.js'
import _mapping from '@/utils/_mapping.js'
export default {
  data() {
    return {
      colorMap: {
        '0': 'green',// 下线颜色
        '1': '#409EFF',//上线颜色
        '2': '#ff0000'//禁用颜色
      },
      statusMap: {
        '0': '下线',
        '1': '上线',
        '2': '禁用'
      },
      settlementStatusMap:{
        '0':'未结算',
        '1':'已结算'
      },
      dialogVisible: false,
      productId: null,
      productNameOption: [],
      productName:'',
      query: {
        pageNum: 1,
        pageSize: 30
      },
      totalNum: 0,
      dateValue: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      tab: {
      },
      loading: false,
      tableData: [],
      fillData: {
          date: '',
          productName: '',
          realCpaNum: '',
          realCpsNum: '',
          uvSwitch: false,
          realUvNum: ''
      }
    }
  },
  methods: {
    toSettlement(item){
      this.$msgbox.confirm(`确认结算该产品?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(() => {
          if(item.settlementStatus===1){
              this.$msg.error(`产品已经结算`)
          }
          let params = {
            id: item.id,
            productId:item.productId,
            settlementStatus: item.settlementStatus,
            noSettlementMoney:item.noSettlementMoney
          }
          _product.settlementProduct(params)
          .then(res => {
            this.$msg.success(`结算成功`)
            this.getSettleMentList()
          })
          .catch(() => {
            this.$msg.error(`${title}失败，请重试`)
          })
        }).catch(() => {
        })
    },
    // 打开录入框
    fillClick(item){
        this.dialogVisible = true
        this.fillData = {
            id: item.id,
            date: _mapping.date_format2(item.createTime),
            productName: item.productName,
            realCpaNum: item.realCpaNum,
            realCpsNum: item.realCpsNum,
            uvSwitch: item.realUvNum > 0 ? true : false,
            realUvNum: item.realUvNum
        }
    },
    // 确定录入
    fillConfirm(){
        let params = {
            id: this.fillData.id,
            realCpaNum: this.fillData.realCpaNum,
            realCpsNum: this.fillData.realCpsNum,
            realUvNum: this.fillData.uvSwitch ? this.fillData.realUvNum : 0,
            settlementType:this.settlementType
        }
        _product.fillData(params)
        .then(res => {
            if(res.data.code === 200){
                this.$msg.success(res.data.msg)
                this.dialogVisible = false
                this.getSettleMentList()
            }else{
                this.$msg.success(res.data.msg)
                this.dialogVisible = false
            }
        })
    },
    // 产品切换
    productChange(item){
        console.log('productId', this.productId)
        this.getSettleMentList()
    },
    renderHeader1(createElement, { column, _self }) {
      console.log(createElement) //  function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
      const label = column.label     
      const labelArr = label.split(' ') 
      console.log('labelArr', labelArr)
      return createElement(
        'span',     //创建最外层的标签可随意
        [
          createElement('span', {  // 创建第一个元素的标签可随意
            attrs: { type: 'text' } 
          },[labelArr[0]]), 
          createElement('p', {  // 创建第二个元素的标签可随意 
            attrs: { type: 'text', style: 'font-size:12px; font-weight:bold; color: #999999;' } // 给分割的某个元素单独加样式
          }, [labelArr[1]])
        ]
      )
    },
    renderHeader2(createElement, { column, _self }) {
      console.log(createElement) //  function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
      const label = column.label     
      const labelArr = label.split(' ') 
      console.log('labelArr', labelArr)
      return createElement(
        'span',     //创建最外层的标签可随意
        [
          createElement('span', {  // 创建第一个元素的标签可随意
            attrs: { type: 'text' } 
          },[labelArr[0]]), 
          createElement('p', {  // 创建第二个元素的标签可随意 
            attrs: { type: 'text', style: 'font-size:12px; font-weight:bold; color: #999999;' } // 给分割的某个元素单独加样式
          }, [labelArr[1], ' ', labelArr[2], ' ', labelArr[3]])
        ]
      )
    },
    renderHeader3(createElement, { column, _self }) {
      console.log(createElement) //  function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
      const label = column.label     
      const labelArr = label.split(' ') 
      console.log('labelArr', labelArr)
      return createElement(
        'span',     //创建最外层的标签可随意
        [
          createElement('span', {  // 创建第一个元素的标签可随意
            attrs: { type: 'text' } 
          },[labelArr[0]]), 
          createElement('p', {  // 创建第二个元素的标签可随意 
            attrs: { type: 'text', style: 'font-size:12px; font-weight:bold; color: #999999;' } // 给分割的某个元素单独加样式
          }, [labelArr[1], ' ', labelArr[2], ' ', labelArr[3], ' ', labelArr[4], ' ', labelArr[5]])
        ]
      )
    },
    renderHeader4(createElement, { column, _self }) {
      console.log(createElement) //  function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
      const label = column.label     
      const labelArr = label.split(' ') 
      console.log('labelArr', labelArr)
      return createElement(
        'span',     //创建最外层的标签可随意
        [
          createElement('span', {  // 创建第一个元素的标签可随意
            attrs: { type: 'text' } 
          },[labelArr[0]]), 
          createElement('p', {  // 创建第二个元素的标签可随意 
            attrs: { type: 'text', style: 'font-size:12px; font-weight:bold; color: #999999;' } // 给分割的某个元素单独加样式
          }, [labelArr[1], ' ', labelArr[2], ' ', labelArr[3], ' ', labelArr[4], ' ', labelArr[5], ' ', labelArr[6], ' ', labelArr[7]])
        ]
      )
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.getSettleMentList()
    },
    handleCurrentChange(val) {
      this.query.pageNum = val
      this.getSettleMentList()
    },
    // 日期改变
    dateChange(val){
      console.log('dateValue', this.dateValue)
      this.getSettleMentList()
    },
    getSettleMentList(){
      let params = {
        productId: this.productId || null,
        pageSize: this.query.pageSize,
        pageNum: this.query.pageNum,
        startTime: !this.dateValue ? "" : this.dateValue[0],
        endTime: !this.dateValue ? "" : this.dateValue[1],
        productName : this.productName
      }
      _product.getProductSettleList(params)
      .then(res => {
          this.tableData = res.data.list || []
          this.totalNum = res.data.total
          this.tab.regisNumTotal = 0
          this.tab.reduceAve = 0
          let realCpaNumTotal = 0
          let realUvNumTotal = 0
          this.tab.productUvNumTotal = 0
          this.tab.productUvRateAve = 0
          this.tab.productBenifitRateTotal = 0
          this.tab.payNumTotal = 0
          if(this.tableData.length > 0){
            this.tableData.forEach((item, index) => {
              realCpaNumTotal += Number(item.realCpaNum)
              realUvNumTotal += Number(item.realUvNum)
              this.tab.regisNumTotal += Number(item.cpaNum)
              this.tab.productUvNumTotal += Number(item.uvNum)
              if(item.settlementType===1){
                this.tab.payNumTotal += Number((item.realUvNum*item.settlementPrice).toFixed(1))
              }else if(item.settlementType===0){
                this.tab.payNumTotal += Number((item.realCpaNum*item.settlementPrice).toFixed(1))
              }else if(item.settlementType===2){
                this.tab.payNumTotal += Number((item.realCpsNum*item.settlementPrice).toFixed(1))
              }
            })
            this.tab.productBenifitRateTotal = isFinite((this.tab.payNumTotal/realUvNumTotal).toFixed(1)) ? (this.tab.payNumTotal/realUvNumTotal).toFixed(1) : '-'
            this.tab.reduceAve = isNaN(((this.tab.regisNumTotal-realCpaNumTotal)*100/this.tab.regisNumTotal).toFixed(1)) ? 0 : ((this.tab.regisNumTotal-realCpaNumTotal)*100/this.tab.regisNumTotal).toFixed(1)
            this.tab.productUvRateAve = isNaN((realCpaNumTotal*100/this.tab.productUvNumTotal).toFixed(1)) ? 0 : (realCpaNumTotal*100/this.tab.productUvNumTotal).toFixed(1) 
          }
      })
    },
    // 刷新按钮
    refreshClick(){
      this.getSettleMentList()
    },
    // 获取产品下啦
    getProductList(){
        _base.getProductList()
        .then(res => {
            console.log('res', res.data)
            if(res.data && res.data.length){
                res.data.map(json => {
                    let item = {}
                    item.value = json.id
                    item.label = json.name
                    this.productNameOption.push(item)
                })
            }
        })
    }
  },
  created(){
    this.dateValue = [this._mapping.date_format2(new Date()), this._mapping.date_format2(new Date())]
    this.getSettleMentList()
    this.getProductList()
  }
}
</script>
<style lang="scss" scoped>
.wrap{
    .dialog{
        .line{
            margin-bottom: 30px;
            .label{
                text-align: center;
                font-weight: bold;
            }
            .red{
                color: #f00;
            }
        }
    }
}
</style>